import store from '../../store'
import http from 'axios'
import db from '../../nedb'
import config from '../../../../package.json'
var fn = {}
/**
 * 写入日志
 */
fn.addLogs = async (data) => {
  try {
    var result = await http.post(store.state.Config.base_url.split('/api')[0] + '/logs/add', data)
    return Promise.resolve(result)
  } catch (e) {
    return Promise.resolve([])
  }
}
/**
 * 格式化时间戳
 */
fn.formatDate = (date, fmt) => {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

/**
 * 格式化时间戳
 */
fn.getObjectURL = (file) => {
  var url = null
  if (window.createObjectURL !== undefined) { // basic
    url = window.createObjectURL(file)
  } else if (window.URL !== undefined) { // mozilla(firefox)
    url = window.URL.createObjectURL(file)
  } else if (window.webkitURL !== undefined) { // webkit or chrome
    url = window.webkitURL.createObjectURL(file)
  }
  return url
}

/**
 * 获取客服详情
 * @param {Number} id 客服ID
 * @param {int} type 获取的方式, 默认0，优先从本地获取 ，为1 从服务器获取最新的
 */
fn.getCuUser = async (id, type) => {
  type = type || 0
  var config = {
    params: {id: id}
  }
  try {
    var locaResult
    if (type === 0) {
      locaResult = await db.csuser_list.getCsUser(id)
    }
    if (locaResult) {
      return Promise.resolve({
        status: 1,
        cs_info: locaResult
      })
    } else {
      var result = await http.get(store.state.Config.base_url + '/csuser/getcsuser', config)
      if (result.data.status) {
        db.csuser_list.addCsUser(result.data.cs_info)
      }
      return Promise.resolve(result.data)
    }
  } catch (e) {
    return Promise.resolve(e)
  }
}

/**
 * 获取客服下面的全部用户
 * @param {Number} id 客服ID
 */
fn.getAlluser = async (id) => {
  var config = {
    params: {butt_id: id}
  }
  try {
    var result = await http.get(store.state.Config.base_url + '/csuser/getalluser', config)
    return Promise.resolve(result.data)
  } catch (e) {
    return Promise.resolve(e)
  }
}
/**
 * 登录接口
 * @param {Object} data 登录信息
 */
fn.postLogin = async (data) => {
  var datas = {
    username: data.username,
    pwd: data.pwd,
    adminLogin: data.adminLogin,
    type: store.state.Config.type
  }
  try {
    var result = await http.post(store.state.Config.base_url + '/login/login', datas)
    return Promise.resolve(result.data)
  } catch (e) {
    return Promise.resolve(e)
  }
}
function padLeftZero (str) {
  return ('00' + str).substr(str.length)
}
/**
 * 获取客服消息列表
 * @param {Number} id 客服ID
 */
fn.getMsguser = async (id) => {
  /**
   * 1.从服务器获取最新的15个联系人
   * 2.同步到本地数据库更新
   * 3.合并后 返回列表
   */
  try {
    var serverUser = await http.get(store.state.Config.base_url + '/user/autopushmsg', {
      params: {cs_id: id}
    })
    var serverUserList = []
    if (serverUser.data.status === 1) serverUserList = serverUser.data.result
    for (var i = 0; i < serverUserList.length; i++) {
      var newmsg = serverUserList[i].chatlog[serverUserList[i].chatlog.length - 1] || {}
      for (var j = 0; j < serverUserList[i].chatlog.length; j++) {
        db.chatlog_list.addChatlog(serverUserList[i].chatlog[j])
      }
      if (serverUserList[i].chatlog.length === 0) {
        serverUserList[i].last_butt_time = serverUserList[i].subscribe_time
      } else {
        serverUserList[i].last_butt_time = newmsg.send_time || 0
      }
      serverUserList[i].butt_id = id
      if (newmsg.type && newmsg.type === 'text') {
        serverUserList[i].last_butt_msg = newmsg.content
      } else if (newmsg.type && newmsg.type === 'image') {
        serverUserList[i].last_butt_msg = '[图片]'
      } else if (newmsg.type && newmsg.type === 'audio') {
        serverUserList[i].last_butt_msg = '[语音]'
      } else if (newmsg.type && newmsg.type === 'video') {
        serverUserList[i].last_butt_msg = '[视频]'
      } else if (newmsg.type && newmsg.type === 'subscribe') {
        serverUserList[i].last_butt_msg = '[新用户关注]'
      } else if (newmsg.type && newmsg.type === 'unsubscribe') {
        serverUserList[i].last_butt_msg = '[用户取关]'
      } else if (newmsg.type && newmsg.type === 'mpnews') {
        serverUserList[i].last_butt_msg = '[图文消息]'
      } else {
        serverUserList[i].last_butt_msg = '[新用户关注]'
      }
      delete serverUserList[i].chatlog
      await db.user_list.addUser(serverUserList[i])
    }
    var sqlUser = await db.user_list.getUser(id)
    var _userlist = {}
    sqlUser.forEach((item) => {
      _userlist[item.user_id] = item
    })
    var _UserLists = []
    Object.keys(_userlist).forEach((item) => {
      _userlist[item].new_msg_num = 0
      _UserLists.push(_userlist[item])
    })
    return Promise.resolve(_UserLists)
  } catch (e) {
    fn.addLogs({
      level: 'Error',
      type: '客户端',
      name: '获取消息列表',
      result: {
        id: id,
        methon: 'fn.getMsguser',
        url: '/api/user/autopushmsg'
      }
    })
    return Promise.resolve([])
  }
}
/**
 * 获取用户详情
 * @param {String} openid 客服Openid
 * @param {int} type 获取的方式, 默认0，优先从服务器获取 ，为1 从服务器获取最新的
 */
fn.getSqlUser = async (openid, type) => {
  type = type || 0
  try {
    var locaResult
    if (type === 0) { // 获取方式为0 ，先从数据库获取。
      locaResult = await db.sql_user.getUser(openid)
    }
    if (!locaResult) { // 本地数据库获取不到， 从服务器获取
      var config = {
        params: {openid: openid}
      }
      var result = await http.get(store.state.Config.base_url + '/user/getsqluser', config)
      if (result.data.status === 1) {
        if (result.data.last_msg && result.data.last_msg[0]) {
          result.data.result.last_butt_time = result.data.last_msg[0].send_time
          if (result.data.last_msg[0].type && result.data.last_msg[0].type === 'text') {
            result.data.result.last_butt_msg = result.data.last_msg[0].content
          } else if (result.data.last_msg[0].type && result.data.last_msg[0].type === 'image') {
            result.data.result.last_butt_msg = '[图片]'
          } else if (result.data.last_msg[0].type && result.data.last_msg[0].type === 'audio') {
            result.data.result.last_butt_msg = '[语音]'
          } else if (result.data.last_msg[0].type && result.data.last_msg[0].type === 'video') {
            result.data.result.last_butt_msg = '[视频]'
          } else {
            result.data.result.last_butt_msg = '[新消息]'
          }
        }
        await db.sql_user.addUser(result.data.result) // 把最新的结果存进数据库
        return Promise.resolve(result.data.result)
      } else {
        throw new Error('获取用户信息失败')
      }
    } else {
      return Promise.resolve(locaResult)
    }
  } catch (e) {
    fn.addLogs({
      level: 'Error',
      type: '客户端',
      name: '获取用户详情',
      result: {
        openid: openid,
        methon: 'fn.getSqlUser',
        url: '/api/user/getsqluser'
      }
    })
    return Promise.resolve(e)
  }
}
/**
 * 从微信后台获取用户信息
 * @param {String} openid 客服Openid
 * @param {String} appid  公众号的appid
 */
fn.getWxUser = async (openid, appid) => {
  var config = {
    params: {
      openid: openid,
      appid: appid
    }
  }
  try {
    var result = await http.get(store.state.Config.base_url + '/user/getuser', config)
    if (result.data.status === 1) {
      return Promise.resolve(result.data)
    } else {
      throw new Error('获取用户信息失败')
    }
  } catch (e) {
    fn.addLogs({
      level: 'Error',
      type: '客户端',
      name: '更新用户详情',
      result: {
        appid: appid,
        openid: openid,
        methon: 'fn.getuser',
        url: '/api/user/getuser'
      }
    })
    return Promise.resolve(e)
  }
}
/**
 * 获取用户聊天记录
 * @param {Object} data
 * @param {Number} data.cs_id 客服ID
 * @param {String} data.openid 用户的OPENID
 * @param {Number} data.last_time 最后时间戳
 */
fn.getChatLog = async (data) => {
  try {
    var result = await http.post(store.state.Config.base_url + '/user/getchatlog', data)
    if (result.data.status === 1) {
      result.data.chatlog.reverse()
      return Promise.resolve(result.data.chatlog)
    } else {
      return Promise.resolve([])
    }
  } catch (e) {
    fn.addLogs({
      level: 'Error',
      type: '客户端',
      name: '获取聊天记录',
      result: {
        data: data,
        methon: 'fn.getChatLog',
        url: '/api/user/getChatLog'
      }
    })
    return Promise.resolve([])
  }
}
/**
 * 发送消息
 */
fn.sendMsgs = async (msg) => {
  try {
    var result
    if (msg.type === 'text') {
      result = await http.post(store.state.Config.base_url + '/user/textmsg', msg)
    } else if (msg.type === 'image') {
      if (msg.media_id) {
        result = await http.post(store.state.Config.base_url + '/user/imgmsg', msg)
      }
    }
    if (result.data.status === 1 && result.data.id) {
      let _data = msg
      _data.id = parseInt(result.data.id)
      db.chatlog_list.addChatlog(_data)
    }
    return Promise.resolve(result.data)
  } catch (e) {
    fn.addLogs({
      level: 'Error',
      type: '客户端',
      name: '发送消息失败',
      result: {
        msg: msg,
        methon: 'fn.sendMsgs'
      }
    })
    return Promise.resolve(e)
  }
}
/**
 * 发送群发消息
 */
fn.sendMassMsgs = async (msg) => {
  try {
    var result
    if (msg.type === 'text') {
      result = await http.post(store.state.Config.base_url + '/user/textmsg', msg)
      // var result = await http.post('https://wechat.shangning.site/api/User/sengMsgForUser', msg)
      return Promise.resolve(result.data)
    } else if (msg.type === 'image') {
      result = await http.post(store.state.Config.base_url + '/user/imgmsg', msg)
      return Promise.resolve(result.data)
    }
  } catch (e) {
    fn.addLogs({
      level: 'Error',
      type: '客户端',
      name: '群发消息',
      result: {
        msg: msg,
        message: e.message,
        methon: 'fn.sendMassMsgs'
      }
    })
    return Promise.resolve(e)
  }
}
/**
 * 验证客服账号登录状态
 */
fn.checkLogin = async (data) => {
  try {
    var datas = {
      user_id: data.cs_id,
      type: 1002,
      key: data.key,
      info: data.info
    }
    var result = await http.post(store.state.Config.base_url + '/login/islogin', datas)
    return Promise.resolve(result.data)
  } catch (e) {
    return Promise.resolve(e)
  }
}
/**
 * 上传文件
 */
fn.uploadImage = async (file) => {
  let config = {headers: {'Content-Type': 'multipart/form-data'}}
  var formdata = new FormData() // 创建FormData数据
  formdata.append('image', file)
  try {
    var result = await http.post(store.state.Config.base_url + '/csuser/uploadpic', formdata, config)
    return Promise.resolve(result.data)
  } catch (e) {
    return Promise.resolve(e)
  }
}
/**
 * 上传图片并获得medioID
 */
fn.getMediaId = async (data) => {
  let config = {headers: {'Content-Type': 'multipart/form-data'}}
  var formdata = new FormData() // 创建FormData数据
  for (var i in data) {
    formdata.append(i, data[i])
  }
  try {
    var result = await http.post(store.state.Config.base_url + '/csuser/getmediaid', formdata, config)
    return Promise.resolve(result.data)
  } catch (e) {
    return Promise.resolve(e)
  }
}
/**
 * 新的上传文件
 */
fn.newUploadImage = async (file) => {
  let config = {headers: {'Content-Type': 'multipart/form-data'}}
  var formdata = new FormData() // 创建FormData数据
  formdata.append('file', file)
  try {
    var result = await http.post('https://a.yougou520.cn/api/Upload/upload', formdata, config)
    return Promise.resolve(result.data)
  } catch (e) {
    return Promise.resolve(e)
  }
}
/**
 * 保存离线消息
 */
fn.saveReplyMsg = async (data) => {
  try {
    var result = await http.post(store.state.Config.base_url + '/csuser/savereply', data)
    return Promise.resolve(result.data)
  } catch (e) {
    return Promise.resolve(e)
  }
}
/**
 * 设置用户在线状态
 */
fn.setUsetType = async (type, csid) => {
  var url = store.state.Config.base_url + '/login/'
  if (type === 1) { // 设置为在线
    url += 'online'
  } else if (type === 2) {
    url += 'busy'
  } else if (type === 3) {
    url += 'outline'
  } else {
    return Promise.resolve({status: -2})
  }
  url = url + '?id=' + csid
  try {
    var result = await http.get(url)
    return Promise.resolve(result.data)
  } catch (e) {
    return Promise.resolve({status: -1})
  }
}
/**
 * 获取客服下面的标签
 * @param {int} auid 公众号的AUID
 * @param {int} type 获取的方式, 默认0，优先从本地获取 ，为1 从服务器获取最新的
 */
fn.getAllTags = async (auid, type) => {
  type = type || 0
  try {
    var locaResult
    if (type === 0) { // 从本地获取优先
      locaResult = await db.tags_list.getTags(auid)
    }
    if (locaResult) {
      return Promise.resolve(locaResult)
    } else {
      var config = {
        params: {auid: auid}
      }
      var result = await http.get(store.state.Config.base_url + '/label/getlabel', config)
      if (!result.data) {
        throw new Error('获取标签失败')
      }
      var list = {}
      result.data.forEach(function (item) {
        if (item.s_label) {
          item.s_label.forEach(function (items) {
            list[items.group_id] = items
          })
        }
      })
      db.tags_list.addTags(auid, {list: list, group: result.data})
      return Promise.resolve({list: list, group: result.data})
    }
  } catch (e) {
    return Promise.resolve({
      list: {},
      group: []
    })
  }
}
/**
 * 设置标签
 */
fn.setUserTags = async (data) => {
  try {
    var result = await http.post(store.state.Config.base_url + '/user/settags', data)
    return Promise.resolve(result)
  } catch (e) {
    return Promise.resolve(e)
  }
}
/**
 * 删除标签
 */
fn.delUserTags = async (data) => {
  try {
    var result = await http.post(store.state.Config.base_url + '/user/deltags', data)
    return Promise.resolve(result)
  } catch (e) {
    return Promise.resolve(e)
  }
}
/**
 * 设置用户额外信息
 */
fn.setUserInfo = async (data) => {
  try {
    var result = await http.post(store.state.Config.base_url + '/csuser/saveusermsg', data)
    return Promise.resolve(result.data)
  } catch (e) {
    return Promise.resolve(e)
  }
}
/**
 * 发送客服离线回复
 */
fn.sendOutline = async (openid) => {
  // 获取对接的客服ID
  var userinfo = await fn.getSqlUser(openid)
  var data = {
    openid: openid,
    butt_id: userinfo.butt_id
  }
  try {
    var result = await http.post(store.state.Config.base_url + '/sendOutline', data)
    return Promise.resolve(result.data)
  } catch (e) {
    return Promise.resolve(e)
  }
}
/**
 * 获取服务端版本
 */
fn.getVersion = async () => {
  // 获取对接的客服ID
  var version = config.version
  try {
    var result = await http.post(store.state.Config.base_url.split('/api')[0] + '/getVersion/?type=1002')
    if (result.data.status === 1) {
      if (result.data.list.length === 0) {
        return Promise.resolve({
          status: -1,
          msg: '服务器没有版本发布'
        })
      }
      var newVersion = result.data.list[0]
      if (newVersion.version === version) {
        return Promise.resolve({
          status: -1,
          msg: '当前已经是最新版本了'
        })
      } else {
        return Promise.resolve({
          status: 1,
          news: newVersion
        })
      }
    } else {
      return Promise.resolve(result.data)
    }
  } catch (e) {
    return Promise.resolve({
      status: -1,
      msg: '获取服务端版本失败！'
    })
  }
}
/**
 * 获取通用常用回复
 * @param {int} auid 公众号的AUID
 * @param {int} type 获取的方式, 默认0，优先从本地获取 ，为1 从服务器获取最新的
 */
fn.getUsual = async (auid, type) => {
  type = type || 0
  try {
    var locaResult
    if (type === 0) {
      locaResult = await db.usual_msg.getUsual(auid)
    }
    if (locaResult) {
      return Promise.resolve(locaResult)
    } else {
      var config = {
        params: {auid: auid}
      }
      var result = await http.get(store.state.Config.base_url + '/csuser/getusual', config)
      if (result.data.status === 1) {
        let msg = []
        result.data.msg.forEach(function (item) {
          msg.push(item.content)
        })
        db.usual_msg.addUsual(auid, msg)
        return Promise.resolve(msg)
      } else {
        return Promise.resolve([])
      }
    }
  } catch (e) {
    return Promise.resolve([])
  }
}
/**
 * 获取自定义常用回复
 * @param {int} csid 客服ID
 * @param {int} type 获取的方式, 默认0，优先从本地获取 ，为1 从服务器获取最新的
 */
fn.getCustomReply = async (csid, type) => {
  type = type || 0
  var config = {
    params: {cs_id: csid}
  }
  try {
    var locaResult
    if (type === 0) {
      locaResult = await db.custom_reply.getCustomReply(csid)
    }
    if (locaResult) {
      return Promise.resolve(locaResult)
    } else {
      var result = await http.get(store.state.Config.base_url + '/csuser/csuser_words', config)
      if (result.data.status === 200) {
        if (result.data.data.length <= 0) {
          throw new Error('获取自定义回复失败')
        }
        let div = document.createElement('div')
        div.innerHTML = result.data.data[0].content
        var list = JSON.parse(div.innerHTML)
        db.custom_reply.addCustomReply(csid, list)
        return Promise.resolve(list)
      } else {
        throw new Error('获取自定义回复失败')
      }
    }
  } catch (e) {
    return Promise.resolve([])
  }
}
/**
 * 设置自定义常用回复
 */
fn.setCustomReply = async (csid, content) => {
  var data = {
    cs_id: csid,
    content: JSON.stringify(content)
  }
  try {
    var result = await http.post(store.state.Config.base_url + '/csuser/csuser_words', data)
    return Promise.resolve(result)
  } catch (e) {
    return Promise.resolve([])
  }
}
fn.maskNewMsg = (msgdata) => {
  if (msgdata.type && msgdata.type === 'text') {
    return msgdata.content
  } else if (msgdata.type && msgdata.type === 'image') {
    return '[图片消息]'
  } else if (msgdata.type && msgdata.type === 'audio') {
    return '[语音消息]'
  } else if (msgdata.type && msgdata.type === 'video') {
    return '[视频消息]'
  } else if (msgdata.type && msgdata.type === 'subscribe') {
    return '[新关注]'
  } else if (msgdata.type && msgdata.type === 'unsubscribe') {
    return '[取消关注]'
  } else {
    return '[新消息]'
  }
}
export default fn
